package com.ckzp.jfinal.interceptor;

import com.ckzp.jfinal.base.csrf.TokenService;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;

/**
 * Created by 51594 on 2022/8/11.
 */
public class TokenInterceptor implements Interceptor {

    @Inject
    TokenService tokenService;

    @Override
    public void intercept(Invocation inv) {
        Controller c = inv.getController();
        String methName = inv.getMethod().getName();
        if (tokenService == null) tokenService = new TokenService();

        // System.out.println("=====================" + methName.startsWith("Edit"));
        //给默认的添加、修改方法添加token
        if (methName.startsWith("Add") || methName.startsWith("Edit") || methName.startsWith("Do")) {
            tokenService.createToken(c);
        }

        //验证token   || methName.startsWith("Del")
        //仅验证 modify
        /**
         * 验证token,仅验证 表单
         * Modify.....Api
         * Modify.....FieldApi不验证
         */
        if (methName.startsWith("Modify") && methName.endsWith("Api") && (!methName.endsWith("FieldApi"))) {
            boolean b = tokenService.validateToken(c);
            if (!b) {
                boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(c.getHeader("X-Requested-With"));
                if (isAjax) {
                    c.renderJson(Ret.fail("msg", "token验证不通过,请刷新页面"));
                } else {
                    c.setAttr("msg", "token验证不通过");
                    c.renderError(403);
                }
                return;
            }
            //添加修改成功后，返回对的页面，此处是解决业务验证不通过的情况，如：添加用户时，
            // 如果存在用户编号，那么需要重新填写，此时就要重新赋值新的token
            tokenService.createToken(c);
        }
        inv.invoke();
    }

}
